//
//  KLMRoomListController.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/20.
//

import UIKit

private let cellId = String(describing: KLMRoomListCell.self)
private let maxRoomCount = 100

enum RoomListType {
    case list   //房间列表  点击查看设备列表
    case move   //移动设备位置 选择房间
    case manage //房间  添加/删除/重命名
}

enum RoomOperateType {
    case add
    case rename
    case delete
}
typealias PopRefreshBlock = (_ roomName: String, _ operateType: RoomOperateType, _ roomCount: Int) -> ()


class KLMRoomListController: KLMBaseController {

    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var doneButton: UIButton!
    // 布局约束
    @IBOutlet weak var collectionViewToBottomCons: NSLayoutConstraint!
    @IBOutlet weak var collectionViewToTopCons: NSLayoutConstraint!
    @IBOutlet weak var collectionViewToTipLabelCons: NSLayoutConstraint!
    @IBOutlet weak var collectionViewToDoneButtonCons: NSLayoutConstraint!
    
    private var deleteStatus = false {
        didSet {
            if operType == .manage {
                for (index, _) in cards.enumerated() {
                    cards[index].isDelete = deleteStatus
                }
                collectionView.reloadData()
            }
        }
    }
    var operType: RoomListType = .list
    var homeId: Int? // 家庭id
    var rooms = [KLMHomeRoom]() {
        didSet {
            if rooms.count > 0 {
                roomNames = rooms.map({ $0.homeRoomName })
            } else {
                roomNames = []
            }
        }
    }
    var cards = [KLMCard]()// 数据源
    var roomNames = [String]()// 房间名称数组
    var popRefreshBlock: PopRefreshBlock?// pop返回回调
    
    
    @IBOutlet weak var collectionView: UICollectionView!
    var lastSelectIndex: IndexPath? {
        didSet {
            if operType == .move {
                doneButton.isEnabled = lastSelectIndex != nil
            }
        }
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        if nibNameOrNil != nil {
            super.init(nibName: nibNameOrNil, bundle: nil)
        } else {
            super.init(nibName: "KLMRoomListController", bundle: nil)
        }
    }
    
    init(homeId: Int, operType: RoomListType) {
        self.homeId = homeId
        self.operType = operType
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = rgba(243, 243, 246, 1)
        collectionView.backgroundColor = rgba(243, 243, 246, 1)
        
        if operType == .manage {
            let rightItem = KLMBaseButton()
            navigationItem.rightBarButtonItem = UIBarButtonItem.itemWithBaseButton(rightItem, target: self, action: #selector(manageList(_:)), configBlock: { baseItem in
                baseItem.configStyle(with: KLMLocalizable.LANGLOC("Manage"), font: UIFont(safeName: "PingFangSC-Regular", size: 18), titleColor: appMainThemeColor)
                baseItem.configStyle(with: KLMLocalizable.LANGLOC("Confirm"), titleColor: appMainThemeColor, state: .selected)
            })
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("KLMRoomListController viewWillAppear...")
        guard let homeId = getNewestHomeId(homeId: self.homeId) else {
            cards = []
            collectionView.reloadData()
            return
        }
        loadHomeRooms(id: homeId)
    }
    // MARK: - 请求房间列表
    func loadHomeRooms(id: Int, success: (() -> ())? = nil) {
        SVProgressHUD.show()
        KLMRequest.queryHomeRoomList(meshId: id) { response in
            SVProgressHUD.dismiss()
            if let roomList = response as? [KLMHomeRoom] {
                self.rooms = roomList
                self.cards = roomList.map({ KLMCard(type: .roomList, title: $0.homeRoomName)
                })
                if self.rooms.count < maxRoomCount {
                    if self.operType == .manage || self.operType == .move {
                        self.cards.append(KLMCard(type: .roomList, subType: .add, title: "添加房间", titleIcon: "add"))
                    }
                }
                if let lastSelectIndex = self.lastSelectIndex, lastSelectIndex.item < self.rooms.count, self.operType == .move {
                    self.cards[lastSelectIndex.item].select = true
                }
                self.collectionView.reloadData()
                if let success = success {
                    success()
                }
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
    
    @objc func manageList(_ item: KLMBaseButton) {
        item.isSelected = !item.isSelected
        deleteStatus = !deleteStatus
    }
    // MARK: - 点击确定按钮，房间移入设备
    @IBAction func tapDoneButton(_ sender: UIButton) {
        
        if let lastSelectIndex = lastSelectIndex, lastSelectIndex.item < rooms.count {
            
            let room = self.rooms[lastSelectIndex.item]
            
            print(self.homeId ?? "未传ID", room.meshId, room.homeRoomId)
            print("当前节点名称：", KLMHomeManager.currentNode.nodeName, KLMHomeManager.currentNode.nodeuuidString)
            KLMHomeMesh.canEditMesh { [weak self] in
                guard let self = self else { return  }
                SVProgressHUD.show()
                // 房间中移入设备
                KLMRequest.homeRoomAddDevice(meshId: self.homeId!, homeRoomId: room.homeRoomId, uuid: KLMHomeManager.currentNode.nodeuuidString) { response in
                    
                    SVProgressHUD.dismiss()
                    self.navigationController?.popViewController(animated: true)
                    if let popRefreshBlock = self.popRefreshBlock {
                        popRefreshBlock(room.homeRoomName, .add, self.rooms.count)
                    }
                    
                } failure: { error in
                    SVProgressHUD.dismiss()
                    KLMHttpShowError(error)
                }
            } failure: {
                
            }

        }
    }
    
    // MARK: - 初始化配置
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        
        if operType == .move {
            tipLabel.configStyle(with: "快速选择", font: UIFont(safeName: "Alata", size: 18), titleColor: rgba(51, 51, 51, 1))
            doneButton.layer.cornerRadius = 22
            doneButton.layer.masksToBounds = true
            doneButton.isEnabled = false
            
            collectionViewToTopCons.priority = .defaultLow
            collectionViewToBottomCons.priority = .defaultLow
            collectionViewToTipLabelCons.priority = .defaultHigh
            collectionViewToDoneButtonCons.priority = .defaultHigh
        } else {
            collectionViewToTopCons.priority = .defaultHigh
            collectionViewToBottomCons.priority = .defaultHigh
            collectionViewToTipLabelCons.priority = .defaultLow
            collectionViewToDoneButtonCons.priority = .defaultLow
            tipLabel.isHidden = true
            doneButton.isHidden = true
        }
        
        let layout = KLMCustomFlowLayout()
        layout.itemSize = CGSizeMake(100, 88)
        collectionView.collectionViewLayout = layout
        
        collectionView.register(UINib(nibName: cellId, bundle: nil), forCellWithReuseIdentifier: cellId)
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    override func applyTheme(_ theme: any Theme) {
        super.applyTheme(theme)
        if operType == .move {
            doneButton.setTitleColor(theme.btnTextColor, for: .normal)
            doneButton.setBackgroundImage(UIImage(color: theme.btnBgColor), for: .normal)
            doneButton.setBackgroundImage(UIImage(color: theme.btnBgColor.withAlphaComponent(0.3)), for: .disabled)
        }
    }
}


extension KLMRoomListController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cards.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = KLMRoomListCell.reusableCellCell(with: collectionView, reuseId: cellId, index: indexPath)
        cell.cellCard = cards[indexPath.item]
        cell.delegate = self
        return cell
    }
}

extension KLMRoomListController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let card = cards[indexPath.item]
        if card.subType == .add {
            if operType == .manage {
                if deleteStatus {
                    SVProgressHUD.showInfo(withStatus: "请先退出编辑模式，再进行操作")
                    return
                }
            }
            //最多定义 100 个房间，创建字符 20 字以内
            if rooms.count < maxRoomCount {
                let vc = KLMBaseModalController(operTitle: card.title, textFieldTip: "请输入房间名称", confirmBlock:  {[weak self] text, type in
                    if type == .addOrRenameRoom {
                        guard let self = self else { return }
                        self.addRoomItem(name: text!)
                    }
                })
                modalVc(vc: vc)
            } else {}
        } else {
            if operType == .list {
                /// 房间列表
                let listVc = KLMAllDevicesController(listType: .homeRoom, homeId: self.homeId, homeRoom: rooms[indexPath.item])
                navigationController?.pushViewController(listVc, animated: true)
            } else if operType == .move {
                /// 移动设备页，点击选中
                selectCardAtIndex(index: indexPath)
            }
        }
    }
    // MARK: - 移动设备，选中某一个房间
    func selectCardAtIndex(index: IndexPath) {
        var card = cards[index.item]
        if let lastIndex = lastSelectIndex {
            if lastIndex != index {
                cards[lastIndex.item].select = false
            }
        }
        card.select = true
        cards[index.item] = card
        collectionView.reloadData()
        lastSelectIndex = index
    }
    // MARK: - 添加一个房间item
    func addRoomItem(name: String) {
        if let homeId = self.homeId {
            SVProgressHUD.show()
            KLMRequest.createHomeRoom(meshId: homeId, homeRoomName: name) { response in
                
                SVProgressHUD.dismiss()
                self.lastSelectIndex = nil
                // 新增房间成功后，请求房间列表
                self.loadHomeRooms(id: homeId) { [weak self] in
                    guard let self = self else { return }
                    if self.operType == .move {
                        // 选中新增的那一个房间
                        let index = self.cards.count == maxRoomCount ? self.cards.count - 1 : self.cards.count - 2
                        self.lastSelectIndex = IndexPath(item: index, section: 0)
                        self.cards[index].select = true
                        self.collectionView.reloadItems(at: [self.lastSelectIndex!])
                        
                    } else if self.operType == .manage {
                        
                        if let popRefreshBlock = self.popRefreshBlock, self.operType == .manage {
                            popRefreshBlock(name, .add, self.rooms.count)
                        }
                    }
                }
            } failure: { error in
                SVProgressHUD.dismiss()
                KLMHttpShowError(error)
            }
        }
    }
}

extension KLMRoomListController: KLMRoomListCellDelegate {
    
    func roomListCellLongPress(cell: KLMRoomListCell, index: IndexPath) {
        if operType != .manage { return }
        
        let mode = cards[index.item]
        let vc = KLMBaseModalController(type: .addOrRenameRoom, operTitle: "房间重命名", textFieldTip: mode.title, confirmBlock:  {
            [weak self] text, type in
            guard let self = self else { return }
            
            if type == .addOrRenameRoom {
                if let homeId = self.homeId {
                    SVProgressHUD.show()
                    let home = rooms[index.item]
                    KLMRequest.updateHomeRoom(meshId: homeId, homeRoomId: home.homeRoomId, homeRoomName: text!) { response in
                        
                        SVProgressHUD.dismiss()
                        
                        self.loadHomeRooms(id: homeId) {
                            if let popRefreshBlock = self.popRefreshBlock {
                                popRefreshBlock(text!, .rename, self.rooms.count)
                            }
                        }
                        
                    } failure: { error in
                        SVProgressHUD.dismiss()
                        KLMHttpShowError(error)
                    }
                }
            }
        })
        modalVc(vc: vc)
    }
    
    /// 删除
    func roomListCellTapDelete(cell: KLMRoomListCell, index: IndexPath) {
        if let homeId = self.homeId {
            SVProgressHUD.show()
            let home = rooms[index.item]
            KLMRequest.deleteHomeRoom(meshId: homeId, homeRoomId: home.homeRoomId) { [self] response in
                
                SVProgressHUD.dismiss()
//                self.cards.remove(at: index.item)
//                self.rooms.remove(at: index.item)
//                self.collectionView.reloadData()
                
                self.loadHomeRooms(id: homeId) {
                    self.deleteStatus = true
                    if let popRefreshBlock = self.popRefreshBlock {
                        popRefreshBlock(home.homeRoomName, .delete, self.rooms.count)
                    }
                }
                
            } failure: { error in
                SVProgressHUD.dismiss()
                KLMHttpShowError(error)
            }
        }
    }
}
